package com.kzw.oa.system.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.kzw.core.util.StringUtil;
import com.kzw.misc.utils.ContextUtil;
import com.kzw.oa.system.model.AppUser;
import com.kzw.oa.system.service.AppUserService;

/**
 * @author zhaoxinguo on 2018/06/05.
 */
@RestController
@RequestMapping("/users")
public class RegisterController {

	@Autowired
    protected AppUserService userService;
    /**
     * 注册用户 默认开启白名单
     * @param user
     */
    @PostMapping("/signup")
    public AppUser signup(@RequestBody AppUser user) {
    	AppUser bizUser = userService.findUniqueBy("username", user.getUsername());
        if(null != bizUser){
            throw new RuntimeException("用户已经存在");
        }
        /*user.setPassword(DigestUtils.md5DigestAsHex((user.getPassword()).getBytes()));*/
        user.setPassword(StringUtil.encryptSha256(user.getPassword()));
        userService.saveOrUpdate(user);
        
        return user;
    }
    
    @GetMapping("/authorityList")
    public List<String> authorityList(){
    	Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        List<String> list = new ArrayList<>();
        for (GrantedAuthority grantedAuthority : authorities) {
            list.add(grantedAuthority.getAuthority());
        }
        
        AppUser user = ContextUtil.getCurrentUser();
        System.out.println(user.getUsername() + ", " + user.getFullname());
        
        return list;
    }


}
